/**
 * title: 审核支公司申请单
 */

import React, { useState, useEffect, useCallback, useRef } from 'react'
import { connect } from 'dva'
import { Button, Checkbox, Modal, Input, Radio, message } from 'antd'
import SearchFrom from '../../components/SearchFrom'
import TableList from '../../components/findTable2'
import dateFormat from '../../Functions/dateFormat'
const { TextArea } = Input
message.config({
  top: '4%',
  duration: 2,
  maxCount: 1
})
// form表单内容
const formArr = [
  {
    labelVal: 'applicationNumber',
    labelText: '申请单编号',
    type: 'Input',
    placeholder: '不支持模糊查询',
  },
  {
    labelVal: 'initiatorCode',
    labelText: '发起机构代码',
    type: 'Input',
    placeholder: '不支持模糊查询',
  },
  {
    labelVal: 'initiatorName',
    labelText: '发起机构名称',
    initialValue: '全部',
    type: 'Select',
    children: ['盐田支公司', '龙岗支公司', '罗湖支公司', '宝安支公司', '新洲支公司', '信息技术部', '车险营业部', '全部']
  },
  {
    labelVal: 'auditStatus',
    labelText: '审批状态',
    type: 'Select',
    initialValue: '全部',
    children: ['待审核', '审批通过', '审批不通过', '已退回', '全部']
  },
  {
    labelVal: 'auditType',
    labelText: '审核类型',
    type: 'Select',
    initialValue: '全部',
    children: ['经营单位工资单审批', '经营单位维护基础数据', '全部']
  }
]

const Application = ({
  applicationData,
  applicationDataTotle,
  getApplicationData,
  setApplicationDataAsync
}) => {
  const [searchFromVal, setSearchFromVal] = useState(null)
  const [selectAll, setSelectAll] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  // 审批模块的Modal显示隐藏控制
  const [visible, setVisible] = useState(false)
  // tabel列表的Modal显示隐藏控制
  const [visibleIndex, setVisibleIndex] = useState('')
  const [newData, setNewData] = useState(null)
  const [radioVal, setRadioVal] = useState('审批通过')
  // TextArea组件
  const text = useRef()

  // 根据筛选条件请求列表数据
  const handleGetApplicationData = useCallback((params) => {
    searchFromVal && getApplicationData({ ...searchFromVal, ...params })
  }, [searchFromVal, getApplicationData])

  // 监听筛选条件的变化，重新请求列表数据
  useEffect(() => {
    handleGetApplicationData()
  }, [searchFromVal, handleGetApplicationData])

  // 获取列表中 auditStatus为'待审核'的数据的key值集合
  useEffect(() => {
    let arr = []
    applicationData.forEach(item => {
      item.auditStatus === '待审核' && arr.push(item.id)
    })
    setSelectAll(arr)
  }, [applicationData])

  // 表格选择功能列
  const rowSelection = {
    selectedRowKeys: selectedRowKeys,
    // 自定义头部标题,全选按钮
    columnTitle () {
      return <Checkbox
        indeterminate={selectedRowKeys.length && selectedRowKeys.length < selectAll.length}
        checked={selectedRowKeys.length && selectedRowKeys.length === selectAll.length}
        onChange={(e) => {
          setSelectedRowKeys(e.target.checked ? selectAll : [])
        }}
      >全选
      </Checkbox>
    },
    onChange (key) {
      setSelectedRowKeys(key)
    },
    getCheckboxProps (record, index) {
      return {
        name: record['id'] + '',
        disabled: record.auditStatus !== '待审核'
      }
    }
  }

  // table表格标题内容
  const columns = [
    {
      title: '序号',
      render (col, row, index) {
        return <span key={row['id']}>{index + 1}</span>
      },
      width: 60
    },
    {
      title: '申请单编号',
      dataIndex: 'applicationNumber',
      width: 98
    },
    {
      title: '申请日期',
      dataIndex: 'applicationDate',
      width: 110
    },
    {
      title: '发起机构代码',
      dataIndex: 'initiatorCode',
      width: 110
    },
    {
      title: '发起机构名称',
      dataIndex: 'initiatorName',
      width: 100
    },
    {
      title: '申请人',
      dataIndex: 'proposer',
      width: 90
    },
    {
      title: '审批类型',
      dataIndex: 'auditType',
      width: 180
    },
    {
      title: '申请内容',
      dataIndex: 'applicationContent',
      width: 150
    },
    {
      title: '申请说明',
      dataIndex: 'applicationExplain',
      width: 120
    },
    {
      title: '系统提示',
      dataIndex: 'prompt',
      width: 120
    },
    {
      title: '审批状态',
      dataIndex: 'auditStatus',
      width: 80
    },
    {
      title: '历次审核意见',
      dataIndex: 'auditOpinion',
      width: 110,
      render (col, row, index) {
        return (
          <>
            <span
              style={{ color: col.length > 6 ? '#1890ff' : '', cursor: 'pointer', width: '100%', minHeight: '24px', display: 'block' }} onClick={() => { setVisibleIndex(index) }}>
              {col.length > 6 ? '查看详情' : col}
            </span>
            <Modal
              centered
              style={{ maxWidth: 350, width: '80%' }}
              title={<span style={{ color: '#444', fontWeight: 500, marginLeft: -10 }}>历次审核意见详情</span>}
              bodyStyle={{ padding: 5 }}
              visible={visibleIndex === index}
              onOk={() => {
                // 点击确认,同步修改数据库的数据
                // 如果 newData 不存在则只修改auditOpinion，存在则将一起修改
                let obj = newData ? { ...newData } : { ...row }
                obj.auditOpinion = text.current.state.value
                setApplicationDataAsync(obj)
                setVisibleIndex('')
              }}
              onCancel={() => {
                setNewData(null)
                setVisibleIndex('')
              }}
            >
              <TextArea ref={text} rows={4} defaultValue={col} />
            </Modal>
          </>
        )
      }
    },
    {
      title: '审核时间',
      dataIndex: 'auditDate',
      width: 125
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 295,
      render (col, row, index) {
        return (
          <div className="operationBtn" key={index}>
            <Button
              type="danger"
              style={{ marginRight: 5 }}
            >查看清单
            </Button>
            <Button
              type="danger"
              style={{ marginRight: 5 }}
            >查看审批流
            </Button>
            <Button
              type="danger"
              disabled={row.auditStatus === '已退回'}
              onClick={() => {
                // 修改该列的数据并暂存至 newState
                let obj = { ...row }
                obj.auditStatus = '已退回'
                obj.auditDate = dateFormat(new Date())
                setNewData(obj)
                // 打开Modal模块进行审核意见输入和退回的确认
                setVisibleIndex(index)
              }}
            >退回
            </Button>
          </div>
        )
      }
    }
  ]

  // 主模块
  return (
    <div className="page-application">
      <SearchFrom formArr={formArr} setSearchFromVal={setSearchFromVal} />
      <div style={{ background: '#fff', textAlign: 'left', textIndent: 5, padding: '10px 0' }}>
        <Button
          type="danger"
          style={{ background: 'rgba(218, 37, 28, 1)', width: 102 }}
          onClick={() => {
            if (applicationData.length && searchFromVal) {
              setVisible(true)
              selectedRowKeys.length || setSelectedRowKeys([selectAll[0]])
            } else {
              message.info('请点击查询')
            }
          }}
        >审批
        </Button>
        <Modal
          centered
          title={<span style={{ color: '#444', fontWeight: 500, marginLeft: -10 }}>审批</span>}
          bodyStyle={{ padding: 5 }}
          visible={visible}
          onOk={() => {
            // 点击确认,同步修改数据库的数据
            selectedRowKeys.forEach(id => {
              let obj = { ...applicationData.find(item => item.id === id) }
              obj.auditOpinion = text.current.state.value
              obj.auditStatus = radioVal
              obj.auditDate = dateFormat(new Date())
              setSelectedRowKeys([])
              setApplicationDataAsync(obj)
            })
            setVisible(false)
          }}
          onCancel={() => setVisible(false)}
        >
          <Radio.Group
            style={{ height: 40, display: 'flex', alignItems: 'center' }}
            onChange={(e) => { setRadioVal(e.target.value) }}
            value={radioVal}>
            <Radio style={{ marginLeft: 30, flex: 1 }} value='审批通过'>审批通过</Radio>
            <Radio style={{ marginLeft: 30, flex: 1 }} value='审批不通过'>审批不通过</Radio>
          </Radio.Group>
          <div style={{ paddingBottom: 10, borderBottom: '1px solid #eee', marginBottom: 10, fontSize: 14, color: '#444' }}>请备注意见 :</div>
          <TextArea style={{ borderColor: '#aaa' }} ref={text} rows={4} />
        </Modal>
      </div>
      <TableList
        className='tablebox'
        bordered
        rowKey="id"
        dataSource={searchFromVal ? applicationData : []}
        columns={columns}
        total={applicationDataTotle}
        setTableList={handleGetApplicationData}
        rowSelection={rowSelection}
      />
    </div >
  )
}

export default connect(
  ({ global: { applicationData, applicationDataTotle } }) => {
    return {
      applicationData,
      applicationDataTotle
    }
  },
  {
    getApplicationData ({ _page = 1, _limit = 7, ...rest }) {
      return {
        type: 'global/getApplicationData', params: { _page, _limit, ...rest }
      }
    },
    setApplicationDataAsync (data) {
      return {
        type: 'global/setApplicationDataAsync', data
      }
    }
  }
)(Application)

